var SHOW_MAX_ELEMENTS = 10;
var PRESENT_DELIM = " -- ";
var MIN_PHRASE_LENGTH = 1;
var MAX_PHRASE_LENGTH = 255;

var Fields = {};

window.onload = function() {
	Fields.searchText = document.getElementById("search_text");
	Fields.foundItems = document.getElementById("found_items_select");
	Fields.updateMother = document.getElementById("update_mother");
	Fields.updateFore = document.getElementById("update_fore");
	Fields.selectedId = document.getElementById("selected_id");
	Fields.insertMother = document.getElementById("insert_mother");
	Fields.insertFore = document.getElementById("insert_fore");
	Fields.insertBatch= document.getElementById("insert_batch_ta");
}

function searchItems() {
	emptyFields();	
	if (isBlank(Fields.searchText)) {
		return false;
	}
	var searchText = Fields.searchText.value;
	if (searchText.length < 1) {
		emptyFields();
		return false;
	}
	if (searchText.length > MAX_PHRASE_LENGTH) {
		return false;
	}
	populateSelectControl(searchText.toLowerCase());	
}


function populateSelectControl(txt) {
		if (typeof txt === 'undefinded' || txt === null) {
			txt = "";
		}
		ajaxGet("/wordage/items/fetchitemsbystring?t=" + txt,
				function() {
				if (xmlhttp.readyState==4 && xmlhttp.status==200) {
					//alert(xmlhttp.responseText);
					populateSelect(xmlhttp.responseText);					
				}
			}
			);
}

function populateSelect(response) {
	// jeigu grąžinama "", tai javascript meta klaidą, nes negali parsinti
	var obj = response ? JSON.parse(response) : {};
	var i;
	for  (i=0; i<obj.length; i++) {
		var optionElement = document.createElement("option");		
		optionElement.value = obj[i]._id;
		optionElement.text = obj[i].mother + PRESENT_DELIM + obj[i].fore;
		try {
			// for IE earlier than version 8
			Fields.foundItems.add(optionElement, selectbox.options[null]);
		}
		catch (e) {
			Fields.foundItems.add(optionElement, null);
		}
	}
	Fields.foundItems.size = SHOW_MAX_ELEMENTS;
}

// _______________________________________________________________________________________
// kai select lauke pasirenkamas koks nors įrašas, pasirinkimas atvaizduojamas
// mother, fore ir id laukuose
function onItemSelected() {
	var selectedText = Fields.foundItems.options[Fields.foundItems.selectedIndex].text;
	var substrings = selectedText.split(PRESENT_DELIM);
	var selectedId = Fields.foundItems.value;
	Fields.updateMother.value = substrings[0];
	Fields.updateFore.value = substrings[1];
	Fields.selectedId.value = selectedId;
	// alert(selectedText + ", " + selectedId);
}

// _________________________________________________________________________________
// pagalbinės laukų išvalymo f-jos

function emptyIfNeeded() {
	// šita yra tam, kad išvalytų laukus, kada 
	// ištrinami visi iki vieno simboliai iš paieškos lauko
	if (trim(Fields.searchText.value).length < 1) {emptyFields();}
}

function emptyFields() {
	var i;
    for(i=Fields.foundItems.length-1;i>=0;i--)  {
        Fields.foundItems.remove(i);
    }
	Fields.updateMother.value = "";
	Fields.updateFore.value = "";
	Fields.selectedId.value = "";
}

// ____________________________________________________________________
// dar kartą pasiklausti, ar tikrai nori viską ištrinti iš lentelės
function reassureTruncateTable() {
	var answer = confirm("Tai tikrai ištrinti visus žodžius iš lentelės?");
	return answer;
}



//____________________________________________________________________
// insertItem()
function insertItem() {
	insItem(Fields.insertMother.value, Fields.insertFore.value);
}

function insItem(mother, fore) {
	var localCheckResult = checkInsertItemFields();
	if (localCheckResult.success) {
		var paramArr = new Array();
		paramArr['mother']=mother;
		paramArr['fore']=fore;
		ajaxPost("/wordage/items/insertitem", paramArr, function() {
			if (xmlhttp.readyState==4 && xmlhttp.status==200) {
				processInsResult(JSON.parse(xmlhttp.responseText));
			}
		});
	} else {
		processInsResult(localCheckResult);
	}
}

function processInsResult(result){
	if (result.success) {
		// empty insert_mother and insert_fore fields
		Fields.insertMother.value = "";
		Fields.insertFore.value = "";
		// refresh select control tam atvejui, jeigu ten
		// buvo koks nors tekstas
		emptyFields();
		populateSelectControl(Fields.searchText.value);
	}
	var messageField = document.getElementById("insertItem_msg");
	
	//set message style
	MessageManager.setMessageStyle(messageField, result.success);
	// show result messages
	messageField.innerHTML = result.messages.join("<br />");
	// attach handlers which remove result message on fields change
	var fields_and_events = [{field:Fields.insertMother, event:"change"},
					          {field:Fields.insertFore, event:"change"},
					          {field:Fields.insertMother, event:"keyup"},
					          {field:Fields.insertFore, event:"keyup"}];
	
	MessageManager.attachHandlers(fields_and_events, messageField);
}

function checkInsertItemFields () {
	var messages = [];
	var success = true;
	if (!fieldLengthBetween(Fields.insertMother, MIN_PHRASE_LENGTH, MAX_PHRASE_LENGTH)) {
		messages.push("Netinkamas frazės gimtąja kalba ilgis");
		success = false;
	}
	if (!fieldLengthBetween(Fields.insertFore, MIN_PHRASE_LENGTH, MAX_PHRASE_LENGTH)) {
		messages.push("Netinkamas frazės užsienio kalba ilgis");
		success = false;
	}
	
	return {messages : messages, success : success};
}

// deletetitem(), updateitem()
//____________________________________________________________________
//deleteitem()

function deleteItem() {
	delById(Fields.selectedId.value);
}

function delById(id) {
	var localCheckResult = checkDeleteItemFields();
	if (localCheckResult.success) {
		ajaxGet("/wordage/items/deleteitem?id=" + id,
			function() {
				if (xmlhttp.readyState==4 && xmlhttp.status==200) {
					//alert(xmlhttp.responseText);
					processDelUpdItemResult(JSON.parse(xmlhttp.responseText));
				}
			}
			);
	} else {
		processDelUpdItemResult(localCheckResult);
	}
	
}

//____________________________________________________________________
// updateItem()

function updateItem() {
	updItem(Fields.selectedId.value, Fields.updateMother.value, Fields.updateFore.value);
}

function updItem(id, mother, fore) {
	var localCheckResult = checkDeleteItemFields();
	if (localCheckResult.success) {
		var paramArr = new Array();
		paramArr['id']=id;
		paramArr['mother']=mother;
		paramArr['fore']=fore;
		ajaxPost("/wordage/items/updateitem", paramArr, function () {
			if (xmlhttp.readyState==4 && xmlhttp.status==200) {
				processDelUpdItemResult(JSON.parse(xmlhttp.responseText));
			}
		});
	} else {
		processDelUpdItemResult(localCheckResult);
	}
}

function processDelUpdItemResult(result) {
	if (result.success) {
		// refresh select control
		emptyFields();
		populateSelectControl(Fields.searchText.value);
	}
	var messageField = document.getElementById("deleteUpdateItem_msg");
	MessageManager.setMessageStyle(messageField, result.success);
	// show result messages
	messageField.innerHTML = result.messages.join("<br />");
	// attach handlers which remove result message on fields change
	var fields_and_events = [{field:Fields.searchText, event:"change"},
					          {field:Fields.foundItems, event:"change"},
					          {field:Fields.updateMother, event:"change"},
					          {field:Fields.updateFore, event:"change"},
					          {field:Fields.searchText, event:"keyup"},
					          {field:Fields.updateMother, event:"keyup"},
					          {field:Fields.updateFore, event:"keyup"}];
	
	MessageManager.attachHandlers(fields_and_events, messageField);
}


function checkDeleteItemFields () {
	var messages = [];
	var success = true;
	if (isBlank(Fields.selectedId) || !fieldIsInt(Fields.selectedId)) {
		messages.push("Neparinkta frazė ištrynimui");
		success = false;
	}	
	return {messages : messages, success : success};
}

function checkUpdateItemFields () {
	var messages = [];
	var success = true;
	if(isBlank(Fields.selectedId) || !fieldIsInt(Fields.selectedId)) {
		messages.push("Neparinkta frazė redagavimui");
		success = false;
		// toliau tikrinti nėra prasmės
		return {messages : messages, success : success};
	}
	
	if (!fieldLengthBetween(Fields.updateMother, MIN_PHRASE_LENGTH, MAX_PHRASE_LENGTH)) {
		messages.push("Netinkamas frazės gimtąja kalba ilgis");
		success = false;
	}
	if (!fieldLengthBetween(Fields.updateFore, MIN_PHRASE_LENGTH, MAX_PHRASE_LENGTH)) {
		messages.push("Netinkamas frazės užsienio kalba ilgis");
		success = false;
	}
	
	return {messages : messages, success : success};
}


//____________________________________________________________________
//insertBatch()
function insertBatch() {
	insBatch(Fields.insertBatch.value);
}

function insBatch(batchText) {
	var localCheckResult = checkInsertBatchFields();
	if (localCheckResult.success) {
		var insertBatchButton = document.getElementById("insert_batch_button");
		insertBatchButton.innerHTML = "Laukite...";
		insertBatchButton.disabled = true;		
		var paramArr = new Array();
		paramArr['b'] = batchText;
		ajaxPost("/wordage/items/insertbatch", paramArr, function() {
			if (xmlhttp.readyState==4 && xmlhttp.status==200) {
				processInsBatchResult(JSON.parse(xmlhttp.responseText));
				insertBatchButton.disabled = false;
				insertBatchButton.innerHTML = "Įrašyti";
			}
		});
	} else {
		processInsBatchResult(localCheckResult);
	}
}

function processInsBatchResult(result){
	// refresh select control tam atvejui, jeigu ten
	// buvo koks nors tekstas
	emptyFields();
	populateSelectControl(Fields.searchText.value);
	
	Fields.insertBatch.value = result.badrows.join("\n");
	// show bad rows
	var messageField = document.getElementById("insertBatch_msg");
	//set message style
	MessageManager.setMessageStyle(messageField, result.success);
	// show result messages
	messageField.innerHTML = result.messages.join("<br />");
	// attach handlers which remove result message on fields change
	var fields_and_events = [{field:Fields.insertBatch, event:"change"},
					          {field:Fields.insertBatch, event:"keyup"},
								{field:messageField, event:"click"}];
	
	MessageManager.attachHandlers(fields_and_events, messageField);
}

function checkInsertBatchFields() {
	var MAX_RECORD_COUNT = 255;
	var CHUNKS_DELIMITER = "|";
	var messages = []
	var taValue = trim((Fields.insertBatch.value).replace(/(<([^>]+)>)/ig,""));
	var success = true;
	// sukapoja į atskiras eilutes
	var rows = taValue.split("\n", MAX_RECORD_COUNT);
	var chunks;
	var firstlength, secondlength;
	
	for (var i=0; i<rows.length; i++) {
		// kiekvieną eilutę kapoti į frazes
		chunks = rows[i].split(CHUNKS_DELIMITER, 3);
		// patikrinti, ar gaunasi lygiai dvi frazės
		if (chunks.length != 2) {
			messages.push("neteisingas " + (i+1) + "-os eilutės formatas.");
			success = false;
		} else {
			// jeigu teisingai kapojasi į dvi frazes,
			// patikrinti, ar teisingi frazių ilgiai
			length1 = (trim(chunks[0])).length;
			length2 = (trim(chunks[1])).length;
			if (length1 < MIN_PHRASE_LENGTH || length1 > MAX_PHRASE_LENGTH) {
				messages.push("blogas " + (i+1) + "-os eilutės pirmosios dalies ilgis.");
				success = false;
			}
			if (length2 < MIN_PHRASE_LENGTH || length2 > MAX_PHRASE_LENGTH) {
				messages.push("blogas " + (i+1) + "-os eilutės antrosios dalies ilgis.");
				success = false;
			}
		}
	}
	
	return {messages : messages, success : success, badrows : rows};
}

//____________________________________________________________________
//truncateTable()
function truncateTable() {
	truncTable();
}

function truncTable(mother, fore) {
	ajaxGet("/wordage/items/truncatetable", function() {
		if (xmlhttp.readyState==4 && xmlhttp.status==200) {
			processTruncTableResult(JSON.parse(xmlhttp.responseText));
		}
	});
}

function processTruncTableResult(result){
	if (result.success) {
		// refresh select control tam atvejui, jeigu ten
		// buvo koks nors tekstas
		emptyFields();
		populateSelectControl(Fields.searchText.value);
	}
	messageField = document.getElementById("truncateTable_msg");
	//set message style
	MessageManager.setMessageStyle(messageField, result.success);
	// show result messages
	messageField.innerHTML = result.messages.join("<br />");
	// attach handlers which remove result message on fields change
	var fields_and_events = [{field:messageField, event:"click"}];	
	MessageManager.attachHandlers(fields_and_events, messageField);
}